package com.zrrd.blog.oauth2.service;


import com.zrrd.blog.api.entities.SysMenu;
import com.zrrd.blog.api.entities.SysUser;
import com.zrrd.blog.api.feign.IFeignSystemController;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IFeignSystemController feignSystemController;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1. 判断用户名是否为空
        if (StringUtils.isEmpty(username)) {
            throw new BadCredentialsException("用户名不允许为空");
        }
        System.out.println(username);
        //2. 通过用户名查询数据库中的用户信息
        SysUser sysUser = feignSystemController.findUserByUsername(username);
        System.out.println(sysUser);
        //3. 用户用户id查询数据库找到对应权限
        List<SysMenu> menuList = feignSystemController.findMenuListByUserIdForLogin(sysUser.getId());
        System.out.println(menuList);
        //4. 封装信息（封装权限标识code）
        List<GrantedAuthority> authorities = null;
        if (CollectionUtils.isNotEmpty(menuList)) {
            authorities = new ArrayList<>();
            for (SysMenu menu : menuList) {
                String code = menu.getCode();
                authorities.add(new SimpleGrantedAuthority(code));
            }
        }
        System.out.println(authorities);
        //5. 构建UserDetail及接口实现类JwtUser
        JwtUser jwtUser = new JwtUser(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(), sysUser.getNickName(),
                sysUser.getImageUrl(), sysUser.getMobile(), sysUser.getEmail(), sysUser.getIsAccountNonExpired(),
                sysUser.getIsAccountNonLocked(), sysUser.getIsCredentialsNonExpired(), sysUser.getIsEnabled(), authorities);
        System.out.println(jwtUser);
        return jwtUser;
    }
}
